"""
Shopify集成API路由模块
提供处理Shopify webhook和注册Shopify店铺的接口
"""
from fastapi import APIRouter, Depends, HTTPException, Request, BackgroundTasks
from sqlmodel import Session
from typing import Dict, Any
from app.database import get_db
from app.services.shopify_service import ShopifyService


# 创建Shopify相关的API路由器
router = APIRouter(prefix="/shopify", tags=["shopify"])
"""Shopify API路由器，所有Shopify相关接口前缀为/shopify，标签为shopify"""


@router.post("/webhook")
async def shopify_webhook(
    request: Request,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db)
):
    """
    Shopify Webhook处理接口
    异步接收和处理来自Shopify的webhook通知，使用后台任务处理耗时操作
    
    Args:
        request (Request): FastAPI请求对象，用于获取请求体和头部信息
        background_tasks (BackgroundTasks): FastAPI后台任务对象，用于异步处理
        db (Session): 数据库会话，通过依赖注入获取
    
    Returns:
        Dict[str, str]: 处理结果
    
    Raises:
        HTTPException: 当缺少必要header时返回400错误
        HTTPException: 当处理webhook失败时返回400错误
    """
    try:
        # 获取原始请求体和解析后的JSON数据
        raw_body = await request.body()
        data = await request.json()
        
        # 从请求头获取webhook主题和店铺域名
        topic = request.headers.get("x-shopify-topic")
        store_domain = request.headers.get("x-shopify-shop-domain")
        
        # 验证必要的header
        if not all([topic, store_domain]):
            raise HTTPException(status_code=400, detail="缺少必要的header")
        
        # 初始化Shopify服务
        shopify_service = ShopifyService(db)
        
        # 添加后台任务处理webhook
        background_tasks.add_task(
            shopify_service.process_shopify_webhook,
            store_domain,
            topic,
            data
        )
        
        # 立即返回成功响应，不等待处理完成
        return {"status": "success"}
        
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/stores")
def register_shopify_store(store_data: Dict[str, Any], db: Session = Depends(get_db)):
    """
    注册Shopify店铺接口
    将新的Shopify店铺信息保存到系统中
    
    Args:
        store_data (Dict[str, Any]): 店铺数据，包含店铺名称、域名、API凭证等
        db (Session): 数据库会话，通过依赖注入获取
    
    Returns:
        Dict[str, Any]: 注册结果
    
    Raises:
        HTTPException: 当注册失败时返回400错误
    """
    # 初始化Shopify服务
    shopify_service = ShopifyService(db)
    try:
        return shopify_service.register_shopify_store(store_data)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))